<template>
  <div class="category-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">添加分类</el-button>
    </div>

    <!-- 分类表格 -->
    <el-table :data="categoryList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="path" label="路径" />
      <el-table-column prop="sort" label="排序" width="100" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.page_size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryList, createCategory, updateCategory, deleteCategory } from '@/api/category'

// 数据列表：存储分类数据
const categoryList = ref([])  // 分类列表数据

// 表单相关：控制对话框和表单状态
const dialogVisible = ref(false)  // 对话框显示状态
const dialogTitle = ref('添加分类')  // 对话框标题
const formRef = ref(null)  // 表单引用，用于验证

// 表单数据对象：存储分类表单的字段
const form = reactive({
  id: null,    // 分类ID，新增时为null
  name: '',    // 分类名称
  path: '',    // 分类路径
  sort: 0      // 排序号
})

// 表单验证规则：定义各字段的验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路径', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 添加分页参数
const pagination = reactive({
  page: 1,
  page_size: 10,
  total: 0
})

// 修改获取分类列表函数
const fetchCategoryList = async () => {
  try {
    const { data } = await getCategoryList({
      page: pagination.page,
      page_size: pagination.page_size
    })
    categoryList.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

// 添加分页变化处理函数
const handlePageChange = (newPage) => {
  pagination.page = newPage
  fetchCategoryList()
}

const handleSizeChange = (newSize) => {
  pagination.page_size = newSize
  pagination.page = 1
  fetchCategoryList()
}

// 添加分类：重置表单并显示对话框
const handleAdd = () => {
  dialogTitle.value = '添加分类'
  form.id = null
  form.name = ''
  form.path = ''
  form.sort = 0
  dialogVisible.value = true
}

// 编辑分类：填充表单数据并显示对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  form.id = row.id
  form.name = row.name
  form.path = row.path
  form.sort = row.sort
  dialogVisible.value = true
}

// 删除分类：确认并调用删除API
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该分类吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCategory({ id: row.id })
      ElMessage.success('删除成功')
      fetchCategoryList()
    } catch (error) {
      ElMessage.error(error.message)
    }
  })
}

// 提交表单：验证并保存分类数据
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updateCategory(form)
        } else {
          await createCategory(form)
        }
        ElMessage.success(form.id ? '更新成功' : '添加成功')
        dialogVisible.value = false
        fetchCategoryList()
      } catch (error) {
        ElMessage.error(form.id ? '更新失败' : '添加失败')
      }
    }
  })
}

// 初始化：页面加载时获取分类列表
fetchCategoryList()
</script>

<style scoped>
/* 分类管理页面容器：添加内边距 */
.category-container {
  padding: 20px;
}

/* 操作栏：底部留出间距 */
.operation-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 